package com.voiceqsologger.service;

import com.voiceqsologger.entity.QsoLog;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 简单通联信息解析器
 * 规则：
 *  - 呼号：字母数字组合，含地区前缀，如 BD1BWV、K1ABC、JA1ZZ 等（近似匹配）
 *  - 信号报告：59 或 599 等
 *  - 设备/天线/位置：基于关键词启发式
 */
@Component
public class QsoParser {

    private static final Pattern CALLSIGN = Pattern.compile("\\b([A-Z]{1,2}\\d[A-Z0-9]{1,3}[A-Z])\\b");
    private static final Pattern RST = Pattern.compile("\\b(59|579|589|599)\\b");

    public QsoLog parse(String text) {
        if (text == null) text = "";
        String norm = text.toUpperCase(Locale.ROOT);
        QsoLog log = new QsoLog();
        log.setRawText(text);
        log.setCreatedAt(LocalDateTime.now());

        Matcher m = CALLSIGN.matcher(norm);
        if (m.find()) {
            log.setCallsign(m.group(1));
        }
        Matcher r = RST.matcher(norm);
        if (r.find()) {
            log.setSignalReport(r.group(1));
        }

        // 设备、天线、位置的启发式提取
        log.setRig(extractAfter(norm, new String[]{"RIG", "RADIO", "TRX"}));
        log.setAntenna(extractAfter(norm, new String[]{"ANT", "ANTENNA"}));
        log.setLocation(extractAfter(norm, new String[]{"QTH", "LOC", "LOCATION"}));
        return log;
    }

    private String extractAfter(String text, String[] keys) {
        for (String k : keys) {
            int idx = text.indexOf(k + ":");
            if (idx >= 0) {
                int start = idx + k.length() + 1;
                int end = Math.min(text.length(), start + 40);
                return text.substring(start, end).replaceAll("[^A-Z0-9 /-]", "").trim();
            }
        }
        return null;
    }
}


